import nodemailer from 'nodemailer'
const { SMTP_EMAIL, SMTP_PASSWORD } = process.env
export class Email {
  private transporter
  constructor(){
    this.transporter = nodemailer.createTransport({
      host: 'smtp.qq.com',
      port: 465,
      secure: true,
      auth: {
        user: SMTP_EMAIL,
        pass: SMTP_PASSWORD,
      },
    })
  }
  // 发送验证码的方法
  send( { email,subject='🫐next-Blueberry🫐验证码'}: {email: string,subject?:string} ) {
    const code = Math.random().toString().slice(-6);
    const options = {
      from: SMTP_EMAIL,
      to: email,
      subject:`🫐next-Blueberry🫐 验证码: ${code}`,
      html: getHtml({code,email}) ,
    };
    return new Promise((resolve,reject)=>{
      this.transporter.sendMail(options, (error, info) => {
        if (error) {
          console.log("邮件发送失败");
          reject(error)
        } else {
          console.log("邮件发送成功");
          resolve(code+'')
        }
      })
    })
  }
}

interface MsgObj {
  [key: string]: string;
}
function getHtml(params: MsgObj) {
  let html = ""
  if (Object.keys(params).length) {
      const formNames: MsgObj = {
          "name": "姓名",
          "email": "邮箱",
          "messenger": "公司",
          "messengerAct": "手机",
          "txt": "留言",
          "code": "🫐验证码"
      }
      for (let k in params) {
          html += `<p style="line-height: 48px;color: #666666;border-bottom: 1px solid #dddddd;">
                      <span style="color: #333333; width: 100px;">${formNames[k]}：</span>
                      ${params[k]}
                  </p>`
      }
  }
  return html
}